from aLiYun import aLiYun
import ujson
from machine import Timer
import utime
import log

CONNECTED = 0
CONNECTING = 1

# 设置日志输出级别
log.basicConfig(level=log.DEBUG)
uart_log = log.getLogger("【Aliyun Operation】")

class Aliyun(object):
    def __init__(self, product_key, dev_name, dev_secret, receive_queue):
        self.aLiY = aLiYun(product_key, None, dev_name, dev_secret)
        self.receive_queue = receive_queue
        self.subscribe_topic = "/" + product_key + "/" + dev_name + "/user/get"
        self.post_topic = "/" + product_key + "/" + dev_name + "/user/update"
        
        
        # # 设置mqtt连接属性
        clientID = b'clientID'  # 自定义字符（不超过64）
        ret = self.aLiY.setMqtt(
            clientID,
            clean_session=False,
            keepAlive=60,
            reconn=True)  # False True

        self.aLiY.setCallback(self.sub_cb)
        self.automatic_operation()
        
        
    def sub_cb(self, topic, payload):
        uart_log.info("topic:{}, payload: {}".format(topic,payload))
        uart_log.debug(type(payload))
        
        str_data = self.parse_aliyun_payload(payload)
        self.receive_queue.put(str_data)
        pass
    
    def automatic_operation(self):
        # 订阅topic
        self.aLiY.subscribe(self.subscribe_topic) 
        
        # 自动登录阿里云
        self.connect_aliyun_server(timeout=5)

    
    def connect_aliyun_server(self, timeout):
        self.aLiY.start()
        uart_log.info('Running')
        time_start = utime.time()
        while self.aLiY.getAliyunSta() != CONNECTED:
            utime.sleep(0.5)
            if (utime.time() - time_start) > timeout:  # 大于5s退出，并提醒用户连接阿里云失败，检查网络连接
                # ShowInClient("上位机连接阿里云失败，请检查网络连接")
                uart_log.error("internet not connect!")
                break
        if self.aLiY.getAliyunSta() == CONNECTED:
            uart_log.info('login aliyun success!')
    
    def publish_topic(self, dict_data, topic=None):
        if self.aLiY.getAliyunSta() == CONNECTED:
            # 1.将字典数据转成json data
            json_data = ujson.dumps(dict_data)

            # 2.发布数据
            uart_log.info("开始发布")
            if topic is None:
                topic = self.post_topic
            self.aLiY.publish(topic, json_data)
    
    def parse_aliyun_payload(self, payload, out_data_type='str'):
        # 输出数据类型为字符串
        if out_data_type == 'str':
            out_data = payload.decode('utf-8')
        elif out_data_type == 'dict':
            out_data = ujson.loads(payload)
        
        uart_log.debug("{} , {}".format(type(out_data), out_data))
        return out_data
        
    def get_aliyun_isConnected(self):
        if self.aLiY.getAliyunSta() == CONNECTED:
            return True
        else:
            return False
        
    


def aliyun_run():
    PRODUCT_KEY = 'h1cpOrLB0iH'
    DEVICE_NAME = 'TBox_Entity'
    DEVICE_SECRET = 'cdb83d9e7f5ab0b6fe38a6c1160ab899'
    aliyun = Aliyun(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET)

    while True:
        pass